package com.qiwenshare.file.config.es;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.validation.constraints.NotNull;
import java.util.stream.Stream;

@Configuration
public class ElasticSearchConfig {

    @Value("${elasticsearch.cluster}")
    @NotNull(message="elasticsearch.cluster is empty")
    private String cluster;

    @Bean
    public ElasticsearchClient elasticsearchClient(){
        HttpHost[] collect = Stream.of(StringUtils.split(cluster,";")).map(HttpHost::create).toArray(HttpHost[]::new);
        RestClient client = RestClient.builder(collect).build();
        ElasticsearchTransport transport = new RestClientTransport(client,new JacksonJsonpMapper());
        return new ElasticsearchClient(transport);
    }
}
